from purest.web import status
import sys
import traceback

class ErrorPrinter:
    """ Outputs stack traces of the given application in the browser. """
    
    def __init__(self, wsgi_app):
        """ wsgi_app is the application whose exception will be handled. """
        self.wsgi_app = wsgi_app
                
    def __call__(self, environ, start_response):
        try:
            return self.wsgi_app(environ, start_response)
        except Exception as error:
            start_response(status.INTERNAL_SERVER_ERROR, 
                           [('Content-Type', 'text/html')],
                           sys.exc_info())
            message =   "<html><head><title>Error: {0}</title></head><body>" + \
            "<h1>Error: {0}</h1><pre>{1}</pre></body></html>"
            title = str(error) if str(error) is not "" \
                    else error.__class__.__name__
            message = message.format(title, traceback.format_exc())
            return [message.encode(encoding='utf_8', errors='strict')]